<template>
    <div>
        <el-header height="36px">
            <header-title :title="title" />
        </el-header>
        <component v-if="prjDetail.prjType" :is="page" v-for="page in pageSetting" :key="page" :ref="page"
            :prj-stage="'AM'" :prj-type="prjDetail.prjType" :process-inst-id="processInstId"
            :prj-id="String(prjDetail.prjId)" />
        <t-page-btn v-if="showtype && btnList.length > 0" :btn-list="btnList" @handleBtn="handleBtn" />

        <!--下一步 -->
        <NextPage v-if="nextVisible" ref="nextPage" :currentNode="currentNode" :visible.sync="nextVisible"
            @doNextEntity="nextPageRes" />
        <!-- 回退 -->
        <NextPage v-if="backVisible" ref="backPage" :currentNode="currentNode" :visible.sync="backVisible"
            @doNextEntity="backPageRes" />
        <!-- 转派 -->
        <TransferPage v-if="transferPageVisible" :visible.sync="transferPageVisible"
            :process-inst-id="workDetail.processInstID" :org-id="workDetail.orgId" :org-code="workDetail.orgCode"
            @redeployEntity="redeployEntity" :showTarnsFer="false" :workDetail="workDetail" />
    </div>
</template>

<script>
import { doNextMessageInfo } from "@/views/speciaCorrection/auxiliary/index"
import HeaderTitle from '@/components/basic/HeaderTitle'
import JnPrjDetail from '@/components/jn/JnPrjDetail.vue'
import ZrAttachmetl from '@/components/zr/ZrAttachmetl.vue'
import JnTaskDetail from '@/components/jn/JnTaskDetail.vue'
import TPageBtn from '@/components/basic/TPageBtn.vue'
import PurchaseOrder from "@/views/speciaCorrection/mainPage/purchaseOrder.vue"
import SpecialCause from "@/views/speciaCorrection/mainPage/otherInfo/specialCause.vue"
import SpecialWastage from "@/views/speciaCorrection/mainPage/otherInfo/specialWastage.vue"
import SpecialCheckPerson from "@/views/speciaCorrection/mainPage/otherInfo/specialCheckPerson.vue"
import { getWFWorkItem } from '@/api/actualBudget/index'
import { pageSetting } from './option'
import NextPage from "./nextPage/NextPage.vue"
import TransferPage from '@/components/nextPerson/ReassignPageNew.vue'
import {
    saveSpecialDetail,
    getPrjDetailApi,
    checkBeforeNextApi,
    checkBeforeNextFinalApi,
    submitNextApi,
    getNextNodeApi,
    getReturnPersonListApi,
} from "@/api/speciaCorrection/index"
import { clonePage } from '@/utils'
export default {
    name: "SpecialCorrection",
    components: {
        HeaderTitle,
        JnPrjDetail,
        SpecialCause,
        SpecialWastage,
        PurchaseOrder,
        SpecialCheckPerson,
        ZrAttachmetl,
        JnTaskDetail,
        TPageBtn,
        NextPage,
        TransferPage
    },
    provide() {
        return {
            prjDetail: () => this.prjDetail,
            workDetail: () => this.workDetail,
        }
    },
    computed: {
        showtype() {
            return this.$route.query.type === 'todo'
        }
    },
    data() {
        return {
            pageSetting,
            title: "",
            btnList: [],
            prjDetail: {},
            workDetail: {},
            processInstId: "",
            SpecialDetailInfo: {},
            nextVisible: false,//下一步
            backVisible: false,//回退
            transferPageVisible: false,//转派
            currentNode: '',
            nodeInfo: {},
            personList: []
        }
    },
    created() {
        const { workItemId, prjId, processInstId } = this.$route.query
        this.processInstId = processInstId || ''
        if (workItemId) {
            this.getWorkDetail(workItemId)
        }
        if (prjId) {
            this.getPrjDetail(prjId)
        }
    },
    methods: {
        // 获取基本信息
        async getPrjDetail(prjId) {
            const { code, data } = await getPrjDetailApi({ prjId: prjId })
            if (+code === 200) {
                this.prjDetail = data
                this.title = this.prjDetail.prjName
            }
        },
        // 获取流程信息
        async getWorkDetail(workItemId) {
            const { code, data } = await getWFWorkItem({ workItemId: workItemId })
            if (+code === 200) {
                this.workDetail = data
                const { bizObject } = data
                await this.getPrjDetail(bizObject.prjId)
                this.processInstId = data?.processInstID
                this.btnList = JSON.parse(bizObject?.buttonConfig) || []
            }
        },
        // 流程按钮
        handleBtn(val) {
            this[val]()
        },
        async doSave(type = true) {
            const doEmit = ['SpecialCause', 'SpecialWastage', 'PurchaseOrder']
            for (let i = 0; i < doEmit.length; i++) {
                if (doEmit[i] !== 'PurchaseOrder') {
                    const { code, message } = this.$refs[doEmit[i]][0]?.submit()
                    if (+code !== 200) {
                        this.$message.warning(message)
                        throw ''
                    }
                }
            }
            // 保存特别修正原因
            const params = {
                adjustId: this.workDetail.bizObject?.bizSeq,
                afterModifyRemark: this.$refs['SpecialCause'][0]?.afterModifyRemark,
                ...this.$refs['SpecialWastage'][0]?.queryParams
            }
            const res = await saveSpecialDetail(params)
            if (+res.code !== 200) {
                throw ""
            }
            // 保存表格信息
           await this.$refs['PurchaseOrder'][0]?.saveInfo(type)
        },
        // 获取下一步节点信息
        async getNextNodeInfo() {
            const params = {
                prjId: this.prjDetail.prjId,
                adjustId: this.workDetail.bizObject?.bizSeq,
                processInstId: this.workDetail.processInstID,
                actInsetId: this.workDetail.activityInstID
            }
            const { code, data } = await getNextNodeApi(params)
            if (+code !== 200) {
                return Promise.reject()
            }
            this.nodeInfo = data[0]
            this.currentNode = this.nodeInfo?.nodeName
        },
        // 下一步
        async doNext() {
            const personObj = {
                field_project_manager: null,
                engineering_accountant: null,
                business_duty: null
            }
            this.personList = this.$refs['SpecialCheckPerson'][0]?.tableData.filter(item => item.nodeId === this.workDetail.activityDefID)
            this.personList.forEach(item => {
                personObj[item.fieldName] = item.empId
            })
            const staffId = JSON.parse(sessionStorage.getItem('SET_LOGINDATA'))?.staffId || ''

            const params = {
                prjId: this.prjDetail.prjId,
                adjustId: this.workDetail.bizObject?.bizSeq
            }
            const doNextParams = {
                ...params,
                processInstId: this.workDetail.processInstID,
                workFlowFlag: 'doNext'
            }
            // 保存
            if(this.workDetail.activityDefID==='correct_01'){
                 await this.doSave(false)
            }
            // 前置校验
            const { code } = await checkBeforeNextFinalApi(doNextParams)
            if (+code !== 200) {
                return Promise.reject()
            }
            await this.getNextNodeInfo()
            const { data } = await checkBeforeNextApi(params)
            const _mesaages = doNextMessageInfo(this.workDetail.activityDefID, staffId, personObj.field_project_manager, personObj.engineering_accountant, personObj.business_duty)
            if (data && _mesaages) {
                this.$alert(`${_mesaages}`, '系统提示', {
                    confirmButtonText: '确定',
                    // 将字符串html化
                    dangerouslyUseHTMLString: true,
                    cancelButtonClass: 'pms-zr-button',
                    confirmButtonClass: 'pms-zr-button-primary',
                    callback: action => {
                        this.nextVisible = true
                    }
                })
            } else {
                this.nextVisible = true
            }
        },
        // 转派
        async doReassign() {
            this.transferPageVisible = true
        },
        // 取消申请
        async doDeleteProc() {
            const params = {
                adjustId: this.workDetail.bizObject?.bizSeq,
                workFlowFlag: "doDeleteProc",
                processInstId: this.workDetail.processInstID,
                nextNodeId: ''
            }
            this.$confirm('是否取消此次特别修正申请？确定则可以取消删除本次项目特别修正流程', '系统提示', {
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                cancelButtonClass: 'pms-zr-button',
                confirmButtonClass: 'pms-zr-button-primary',
                type: 'warning'
            }).then(async () => {
                const { code } = await submitNextApi(params)
                if (+code === 200) {
                    this.$alert(`取消成功`, '系统提示', {
                        confirmButtonText: '确认',
                        cancelButtonClass: 'pms-zr-button',
                        callback: action => {
                            clonePage()
                        }
                    })
                }
            }).catch(() => {
                console.log("cancel");
            })

        },
        // 回退
        async doBack() {
            const params = {
                prjId: this.prjDetail.prjId,
                adjustId: this.workDetail.bizObject?.bizSeq,
                processInstId: this.workDetail.processInstID,
                workFlowFlag: 'doBack'
            }
            // 前置校验
            const { code } = await checkBeforeNextFinalApi(params)

            if (+code !== 200) {
                return Promise.reject()
            }

            const { data } = await getReturnPersonListApi({
                processInstId: this.workDetail.processInstID
            })
            this.nodeInfo = data[0]
            this.currentNode = this.nodeInfo?.nodeName
            this.backVisible = true
        },
        // 关闭
        async doClose() {
            clonePage()
        },
        // 下一步确认
        async nextPageRes(data) {
            const result = this.$refs['SpecialCheckPerson'][0]?.tableData.filter(item => item.nodeId === this.nodeInfo?.nodeId)
            // 去重
            const uniqueArr = result.filter((item, index) =>
                result.findIndex(i => i.loginName === item.loginName) === index
            );
            const params = {
                adjustId: this.workDetail.bizObject?.bizSeq,
                prjId: this.prjDetail.prjId,
                nextNodeId: this.nodeInfo?.nodeId,
                nextNodeName: this.nodeInfo?.nodeName,
                userIds: uniqueArr.map(item => item.loginName).join(','),
                templateId: this.workDetail.processDefName,
                workFlowFlag: "doNext",
                processInstId: this.workDetail.processInstID,
                workItemId: this.$route.query.workItemId,
                opinion: data.opinion,
                detailId: this.nodeInfo?.detailId,
            }
            const { code } = await submitNextApi(params)
            if (+code === 200) {
                this.$alert(`提交成功`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        clonePage()
                    }
                })
            }
        },
        // 回退确认
        async backPageRes(data) {
            const params = {
                adjustId: this.workDetail.bizObject?.bizSeq,
                prjId: this.prjDetail.prjId,
                nextNodeId: this.nodeInfo?.nodeId,
                nextNodeName: this.nodeInfo?.nodeName,
                userIds: this.nodeInfo?.userId,
                templateId: this.workDetail.processDefName,
                workFlowFlag: "doBack",
                processInstId: this.workDetail.processInstID,
                workItemId: this.$route.query.workItemId,
                opinion: data.opinion,
                detailId: this.nodeInfo?.detailId,
            }
            const { code } = await submitNextApi(params)
            if (+code === 200) {
                this.$alert(`提交成功`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        clonePage()
                    }
                })
            }
        },
        // 转派确认
        async redeployEntity(data) {
            const params = {
                adjustId: this.workDetail.bizObject?.bizSeq,
                prjId: this.prjDetail.prjId,
                workFlowFlag: "doReassign",
                templateId: this.workDetail.processDefName,
                nextNodeId: data.nodeId,
                nextNodeName: data?.nodeName,
                workItemId: this.workDetail.workItemID,
                opinion: data.opinion,
                userIds: data.userId ? data.userId : data.empId,
                processInstId: this.workDetail.processInstID,
                detailId: data?.detailId
            }
            const { code } = await submitNextApi(params)
            if (+code === 200) {
                this.$alert(`转派成功`, '系统提示', {
                    confirmButtonText: '确认',
                    cancelButtonClass: 'pms-zr-button',
                    callback: action => {
                        clonePage()
                    }
                })
            }
        }
    }
}

</script>
<style lang="scss" scoped></style>
